<template>
  <div class="dashboard">
    <h2>数据可视化仪表板</h2>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon archive-icon">
              <i class="el-icon-folder"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.totalArchives || 0 }}</div>
              <div class="stat-label">总档案数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon notice-icon">
              <i class="el-icon-bell"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.publishedNotices || 0 }}</div>
              <div class="stat-label">已发布公告</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon training-icon">
              <i class="el-icon-reading"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.publishedTrainings || 0 }}</div>
              <div class="stat-label">培训资料</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon request-icon">
              <i class="el-icon-edit-outline"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.pendingModificationRequests || 0 }}</div>
              <div class="stat-label">待处理申请</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>档案状态分布</span>
          </div>
          <div id="archiveStatusChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>修改申请状态统计</span>
          </div>
          <div id="requestStatusChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新动态 -->
    <el-row :gutter="20" class="activity-row">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>最新公告</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="viewAllNotices">查看全部</el-button>
          </div>
          <div v-if="recentNotices.length > 0">
            <div v-for="notice in recentNotices" :key="notice.noticeId" class="activity-item">
              <div class="activity-title">{{ notice.title }}</div>
              <div class="activity-time">{{ formatDate(notice.publishTime) }}</div>
            </div>
          </div>
          <div v-else class="no-data">暂无公告</div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>系统日志</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="viewAllLogs">查看全部</el-button>
          </div>
          <div v-if="recentLogs.length > 0">
            <div v-for="log in recentLogs" :key="log.logId" class="activity-item">
              <div class="activity-title">{{ log.action }}</div>
              <div class="activity-details">{{ log.actionDetails }}</div>
              <div class="activity-time">{{ formatDate(log.timestamp) }}</div>
            </div>
          </div>
          <div v-else class="no-data">暂无日志</div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import service from '@/utils/request'

export default {
  name: 'Dashboard',
  data() {
    return {
      statistics: {},
      recentNotices: [],
      recentLogs: [],
      loading: false
    }
  },
  mounted() {
    this.loadDashboardData()
  },
  methods: {
    async loadDashboardData() {
      this.loading = true
      try {
        // 加载统计数据
        await this.loadStatistics()
        // 加载最新公告
        await this.loadRecentNotices()
        // 加载系统日志
        await this.loadRecentLogs()
        // 初始化图表
        this.$nextTick(() => {
          this.initCharts()
        })
      } catch (error) {
        this.$message.error('加载仪表板数据失败')
      }
      this.loading = false
    },
    
    async loadStatistics() {
      try {
        console.log('开始加载统计数据...')
        const response = await service.get('/api/dashboard/statistics')
        console.log('API响应:', response)
        if (response.data.code === 200) {
          this.statistics = response.data.data
          console.log('统计数据:', this.statistics)
        } else {
          console.error('API返回错误:', response.data)
          this.$message.error('获取统计数据失败: ' + response.data.message)
        }
      } catch (error) {
        console.error('加载统计数据失败', error)
        this.$message.error('网络错误，请检查后端服务是否正常运行')
      }
    },
    
    async loadRecentNotices() {
      try {
        const response = await service.get('/api/notices/published')
        if (response.data.code === 200) {
          this.recentNotices = response.data.data.slice(0, 5) // 只显示最新5条
        }
      } catch (error) {
        console.error('加载最新公告失败', error)
      }
    },
    
    async loadRecentLogs() {
      try {
        const response = await service.get('/api/system-logs/page?current=1&size=5')
        if (response.data.code === 200) {
          this.recentLogs = response.data.data.records || []
        }
      } catch (error) {
        console.error('加载系统日志失败', error)
      }
    },
    
    initCharts() {
      this.initArchiveStatusChart()
      this.initRequestStatusChart()
    },
    
    initArchiveStatusChart() {
      const chartDom = document.getElementById('archiveStatusChart')
      if (!chartDom) return
      
      const myChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '档案状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: this.statistics.activeArchives || 0, name: '活跃档案' },
              { value: (this.statistics.totalArchives || 0) - (this.statistics.activeArchives || 0), name: '其他状态' }
            ],
            itemStyle: {
              color: function(params) {
                const colors = ['#3498db', '#95a5a6']; // 蓝色，灰色
                return colors[params.dataIndex];
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      myChart.setOption(option)
    },
    
    initRequestStatusChart() {
      const chartDom = document.getElementById('requestStatusChart')
      if (!chartDom) return
      
      const myChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: ['待审批', '已批准', '已拒绝', '已完成'],
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '申请数量',
            type: 'bar',
            barWidth: '60%',
            data: [
              this.statistics.pendingModificationRequests || 0,
              this.statistics.approvedModificationRequests || 0,
              this.statistics.rejectedModificationRequests || 0,
              this.statistics.completedModificationRequests || 0
            ],
            itemStyle: {
              color: function(params) {
                const colors = ['#f39c12', '#27ae60', '#e74c3c', '#3498db']; // 橙色，绿色，红色，蓝色
                return colors[params.dataIndex];
              }
            }
          }
        ]
      }
      myChart.setOption(option)
    },
    
    viewAllNotices() {
      this.$router.push('/notice-management')
    },
    
    viewAllLogs() {
      this.$router.push('/system-logs')
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString()
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.archive-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.notice-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.training-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.request-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.charts-row {
  margin-bottom: 20px;
}

.activity-row {
  margin-bottom: 20px;
}

.activity-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.activity-details {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.activity-time {
  font-size: 12px;
  color: #c0c4cc;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}
</style> 